package com.sywb.chuangyebao.view.video;

import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.adapter.ScrollSpeedLinearLayoutManger;
import com.sywb.chuangyebao.bean.SuperInfo;
import com.sywb.chuangyebao.bean.VideoData;
import com.sywb.chuangyebao.library.player.view.FlingRecyclerView;
import com.sywb.chuangyebao.utils.HttpCallback;
import com.sywb.chuangyebao.utils.HttpUtils;

import org.bining.footstone.adapter.listener.OnLoadMoreListener;
import org.bining.footstone.log.Logger;
import org.bining.footstone.rxjava.rxbus.annotation.Subscribe;
import org.bining.footstone.rxjava.rxbus.annotation.Tag;
import org.bining.footstone.rxjava.rxbus.thread.ThreadMode;
import org.bining.footstone.view.BaseFragment;
import org.bining.footstone.widget.PullToRefreshView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 视频列表
 */
public class VideoListFragment extends BaseFragment {

    private PullToRefreshView commonRefresh;
    private FlingRecyclerView frvVideo;

    private RelativeLayout commonNodata;
    private TextView commonNodataContent;
    private ImageView commonNodataIcon;
    private TextView commonNodataSubtitle;

    private FrameLayout flFullScreen;

    private int fragmentWhereTab;
    private int uid;

    private boolean isVisibleToTab = true;// 当前Fragemnt所在的Tab页是否可见
    private boolean isVisibleToUser = false;// 当前Fragemnt是否对用户可见
    private boolean orientation;// 是否为横屏

    //是否处于滚动状态
    private boolean mScrollState = false;

    // item 相关位置信息
    private int lastItemPosition = 0;// 可见的第一个Item位置
    private int firstItemPosition = 0;// 可见的最后一个Item位置
    private int visibleItemCount = 0;// 可见的Item个数
    private int itemPosition = 0;// item 的位置
    private int playerPosition = -1;// 正在播放item 的位置

    private int pageNumber = 1;

    private VideoAdapter videoAdapter;

    /**
     * Fragment 实例
     */
    public static VideoListFragment newInstance(Object... pramars) {
        VideoListFragment fragment = new VideoListFragment();
        if (pramars != null && pramars.length > 0) {
            Bundle bundle = new Bundle();
            for (int i = 0; i < pramars.length; i++) {
                bundle.putSerializable("p" + i, (Serializable) pramars[i]);
            }
            fragment.setArguments(bundle);
        }
        return fragment;
    }

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.fragment_video;
    }

    @Override
    public void initView(View view, Bundle bundle) {
        if (bundle != null) {
            fragmentWhereTab = bundle.getInt("p0", 0);
            uid = bundle.getInt("p1", -1);
        } else {
            fragmentWhereTab = getArguments().getInt("p0", 0);
            uid = getArguments().getInt("p1", -1);
        }

        commonRefresh = (PullToRefreshView) getView(R.id.common_refresh);
        frvVideo = (FlingRecyclerView) getView(R.id.common_recycler);
        commonNodata = (RelativeLayout) getView(R.id.common_nodata);
        commonNodataContent = (TextView) getView(R.id.common_nodata_content);
        commonNodataIcon = (ImageView) getView(R.id.common_nodata_icon);
        commonNodataSubtitle = (TextView) getView(R.id.common_nodata_subtitle);
        flFullScreen = (FrameLayout) getView(R.id.fl_fullscreen);

        commonRefresh.setOnRefreshListener(new PullToRefreshView.OnRefreshListener() {
            @Override
            public void onRefresh(PullToRefreshView pullToRefreshLayout) {
                stopPlayer(frvVideo, playerPosition);
                pageNumber = 1;
                getVideoList();
            }
        });

        frvVideo.addOnScrollListener(new MyScrollListener());
        frvVideo.setLayoutManager(new ScrollSpeedLinearLayoutManger(mActivity));

        videoAdapter = new VideoAdapter(mActivity, uid);
        videoAdapter.setLoadingView(R.layout.layout_loading);
        videoAdapter.setPageSize(Constants.PAGESIZE);
        videoAdapter.setLoadMoreEnable(true);
        videoAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMoreClick() {
                pageNumber++;
                getVideoList();
            }
        });
        videoAdapter.setVideoHolderCallback(new MyVideoHolderCallback());
        frvVideo.setAdapter(videoAdapter);

        initData();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt("p0", fragmentWhereTab);
        outState.putInt("p1", uid);
        super.onSaveInstanceState(outState);
    }

    private void initData() {
        showProgress();
        getVideoList();
    }

    private void getVideoList() {
        HttpUtils.getContentList(Constants.TOPIC_TYPE_VIDEO, uid < 0 ? null : String.valueOf(uid), null, pageNumber, null, "1", "1", new HttpCallback<List<SuperInfo>>() {
            @Override
            public void onSuccess(List<SuperInfo> superInfos) {
                List<VideoData> videoDataList = new ArrayList<>();
                if (superInfos != null) {
                    for (SuperInfo superInfo : superInfos) {
                        VideoData videoData = JSON.parseObject(superInfo.content, VideoData.class);
                        videoDataList.add(videoData);
                    }
                }
                if (pageNumber == 1) {
                    commonRefresh.refreshFinish(true);
                    if (videoAdapter.getDataCount() > 0) {
                        List<VideoData> oldDatas = videoAdapter.getDatas();
                        videoDataList.addAll(oldDatas);
                    }
                    videoAdapter.clearDatas();
                    playerPosition = 0;
                }
                videoAdapter.notifyDataChangedAfterLoadMore(videoDataList);
            }

            @Override
            public void onError(String strMsg) {
                super.onError(strMsg);
                if (pageNumber == 1) {
                    commonRefresh.refreshFinish(true);
                } else {
                    commonRefresh.loadmoreFinish(true);
                }
                showMessage(strMsg);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                hideProgress();
                isNoData();
            }
        });
    }

    public void isNoData() {
        boolean isNoData = videoAdapter.getDataCount() == 0;
        if (!isNoData && pageNumber == 1 && playerPosition >= 0) {
            Logger.e("isNoData startPlayer " + playerPosition);
            startPlayer(frvVideo, playerPosition);
//            if (!startPlayer(frvVideo, playerPosition)) {
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        startPlayer(frvVideo, playerPosition);
//                    }
//                }, 1000);
//            }
        }
        commonNodata.setVisibility(isNoData ? View.VISIBLE : View.GONE);
    }

    /**
     * 列表的滚动监听
     */
    private class MyScrollListener extends RecyclerView.OnScrollListener {

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            Logger.e("onScrollStateChanged");
            super.onScrollStateChanged(recyclerView, newState);
            switch (newState) {
                case RecyclerView.SCROLL_STATE_DRAGGING:// 用户用手指滚动
                    mScrollState = true;
                    break;
                case RecyclerView.SCROLL_STATE_SETTLING:// 自动滚动
                    mScrollState = true;
                    break;
                case RecyclerView.SCROLL_STATE_IDLE:// 停止滑动
                    mScrollState = false;
                    //滑动停止和松开手指时，调用此方法 进行播放
                    if (playerPosition != itemPosition) {
                        if (playerPosition >= firstItemPosition && playerPosition <= lastItemPosition) {
                            if (getVisibilityPercents(recyclerView, playerPosition - firstItemPosition) < 95) {
                                startPlayer(recyclerView, itemPosition);
                            }
                        } else {
                            startPlayer(recyclerView, itemPosition);
                        }
                    }
                    break;
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            Logger.e("onScrolled");
            RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
            if (layoutManager instanceof LinearLayoutManager) {
                LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
                // 获取第一个可见view的位置
                firstItemPosition = linearManager.findFirstVisibleItemPosition();
                //  获取最后一个可见view的位置
                lastItemPosition = linearManager.findLastVisibleItemPosition();
                // 获取可见view的总数
                visibleItemCount = linearManager.getChildCount();
                if (mScrollState) {// 滚动
                    srcollVisible(recyclerView, firstItemPosition, lastItemPosition, visibleItemCount);
                }
                // Activity 中自动播放第一个
                // else { // 停止 进入时调用此方法，进行播放第一个
                // if (playerPosition != itemPosition) {
                // startPlayer(recyclerView, itemPosition);
                // }
                // }
            }
        }
    }

    /**
     * 滚动时 判断哪个view 显示百分比最大，哪个最大 视图亮起
     */
    private void srcollVisible(RecyclerView recyclerView, int firstItemPosition, int lastItemPosition, int visibleItemCount) {
        int position = 0; // 最大显示百分比的屏幕内的子view的位置
        for (int i = 0; i < visibleItemCount; i++) {
            if (getVisibilityPercents(recyclerView, i) >= 95) {
                position = i;
                break;
            }
        }
        itemPosition = (firstItemPosition + position);
        Logger.e("itemPosition:" + itemPosition + " playerPosition:" + playerPosition + " firstItemPosition:" + firstItemPosition + " lastItemPosition:" + lastItemPosition + " visibleItemCount:" + visibleItemCount);
        if (playerPosition != itemPosition && playerPosition >= 0) {
            if (playerPosition >= firstItemPosition && playerPosition <= lastItemPosition) {
                if (getVisibilityPercents(recyclerView, playerPosition - firstItemPosition) < 95) {
                    stopPlayer(recyclerView, playerPosition);
                }
            } else {
                stopPlayer(recyclerView, playerPosition);
            }
        }
    }

    /**
     * 获取指定位置的Item的可见百分比
     */
    private int getVisibilityPercents(RecyclerView recyclerView, int position) {
        int visibilityPercents = 0;
        if (recyclerView != null) {
            View childAt = recyclerView.getChildAt(position).findViewById(R.id.ll_container);

            Rect mCurrentViewRect = new Rect();

            childAt.getLocalVisibleRect(mCurrentViewRect);

            int height = childAt.getHeight();
            int top = mCurrentViewRect.top;
            int bottom = mCurrentViewRect.bottom;

            if (top >= 0) {
                visibilityPercents = (bottom - top) * 100 / height;
            } else if (bottom < 0) {
                visibilityPercents = 0;
            }
        }
        return visibilityPercents;
    }

    /**
     * 添加播放器并开始播放视频，并获取之前的播放进度
     */
    private void startPlayer(RecyclerView recyclerView, int position) {
        if (isVisibleToUser && isVisibleToTab) {
            Logger.e("startPlayer " + position);
            VideoHolder childViewHolder = (VideoHolder) recyclerView.findViewHolderForAdapterPosition(position);
            if (childViewHolder != null) {
                // 注册监听以及隐藏蒙层
                childViewHolder.start();
            } else {
                Logger.e("未取到对应位置的VideoHolder：" + position);
            }
        }
    }

    /**
     * 停止播放视频
     */
    private void stopPlayer(RecyclerView recyclerView, int position) {
        Logger.e("stopPlayer " + position);
        VideoHolder childViewHolder = (VideoHolder) recyclerView.findViewHolderForAdapterPosition(position);
        if (childViewHolder != null) {
            childViewHolder.pause();
        }
    }

    private void playerNext(int position) {
        if (position < (videoAdapter.getDataCount() - 1)) {
            frvVideo.smoothScrollToPosition(position + 1);
        }
    }

    private class MyVideoHolderCallback implements OnVideoHolderCallback {

        @Override
        public void onStarted(int position) {
            if (playerPosition != position) {
                VideoHolder childViewHolder = (VideoHolder) frvVideo.findViewHolderForAdapterPosition(playerPosition);
                if (childViewHolder != null) {
                    childViewHolder.pause();
                }
            }
            playerPosition = position;
        }

        @Override
        public void onPaused(int position) {
        }

        @Override
        public void onCompletion(int position) {
            playerNext(position);
        }

        @Override
        public void onError(int position, int causeCode, int sceneCode, String message) {
        }

        @Override
        public void onClickScreenDirection(int position, long currentPosition) {
        }

        @Override
        public void intentUser(int position) {
        }

        @Override
        public void intentPraise(int position) {
        }

        @Override
        public void intentComment(int position) {
        }

        @Override
        public void intentShare(int position) {
        }
    }

    @Subscribe(thread = ThreadMode.MAIN_THREAD, tags = {@Tag(ConnectivityManager.CONNECTIVITY_ACTION)})
    public void netwotkChange(String data) {
        Logger.e("收到网络改变广播");
        if (playerPosition >= 0) {
            VideoHolder childViewHolder = (VideoHolder) frvVideo.findViewHolderForAdapterPosition(playerPosition);
            if (childViewHolder != null) {
                childViewHolder.inspectPlayer();
            }
        }
    }

//    /**
//     * 横竖屏切换
//     */
//    @Override
//    public void onConfigurationChanged(Configuration newConfig) {
//        super.onConfigurationChanged(newConfig);
//        aliPlayerView.onConfigurationChanged(newConfig);
//        if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {// 竖屏
//            orientation = false;
//
//            flFullScreen.setVisibility(View.GONE);
//            flFullScreen.removeAllViews();
//
//            Adosorber.hidePlayerFromView(mActivity);
//
//            VideoHolder childViewHolder = (VideoHolder) frvVideo.findViewHolderForAdapterPosition(itemPosition);
//            if (childViewHolder != null) {
//                View itemView = childViewHolder.itemView;
//                FrameLayout frameLayout = itemView.findViewById(R.id.ll_video);
//                if (frameLayout.getChildCount() > 0) {
//                    frameLayout.removeAllViews();
//                }
//                ViewGroup lastParent = (ViewGroup) aliPlayerView.getParent();
//                if (lastParent != null && lastParent.getChildCount() > 0) {
//                    lastParent.removeAllViews();
//                }
//
//                Adosorber.showPlayerToView(mActivity, childViewHolder.llVideo, frvVideo);
//            }
//
//            int mShowFlags = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
//            flFullScreen.setSystemUiVisibility(mShowFlags);
//        } else { // 横屏
//            orientation = true;
//
//            ViewGroup lastParent = (ViewGroup) aliPlayerView.getParent();
//            if (lastParent != null && lastParent.getChildCount() > 0) {
//                lastParent.removeAllViews();
//            }
//
//            flFullScreen.addView(aliPlayerView);
//            flFullScreen.setVisibility(View.VISIBLE);
//
//            int mHideFlags = View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
//            flFullScreen.setSystemUiVisibility(mHideFlags);
//        }
//    }

    @Override
    public void onStart() {
        Logger.e("onStart");
        super.onStart();
    }

    /**
     * Activity 重新进入前台 播放逻辑
     */
    @Override
    public void onResume() {
        Logger.e("onResume");
        if (isVisibleToUser && isVisibleToTab && playerPosition >= 0) {
            VideoHolder childViewHolder = (VideoHolder) frvVideo.findViewHolderForAdapterPosition(playerPosition);
            if (childViewHolder != null) {
                childViewHolder.autoResume();
            }
        }
        super.onResume();
    }

    /**
     * Activity 不在前台时 暂停播放
     */
    @Override
    public void onPause() {
        Logger.e("onPause");
        if (playerPosition >= 0) {
            VideoHolder childViewHolder = (VideoHolder) frvVideo.findViewHolderForAdapterPosition(playerPosition);
            if (childViewHolder != null) {
                childViewHolder.autoPause();
            }
        }
        super.onPause();
    }

    @Override
    public void onStop() {
        Logger.e("onStop");
        super.onStop();
    }

    /**
     * Activity 销毁时 销毁播放器
     */
    @Override
    public void onDestroy() {
        Logger.e("onDestroy");
        for (int i = 0; i < videoAdapter.getDataCount(); i++) {
            VideoHolder childViewHolder = (VideoHolder) frvVideo.findViewHolderForAdapterPosition(i);
            if (childViewHolder != null) {
                childViewHolder.destroy();
            }
        }
        super.onDestroy();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Logger.e("setUserVisibleHint：" + isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        if (videoAdapter != null && videoAdapter.getDataCount() > 0) {
            if (playerPosition < 0) {
                if (isVisibleToUser && isVisibleToTab) {
                    startPlayer(frvVideo, itemPosition);
                }
            } else {
                VideoHolder childViewHolder = (VideoHolder) frvVideo.findViewHolderForAdapterPosition(playerPosition);
                if (childViewHolder != null) {
                    if (isVisibleToUser && isVisibleToTab) {
                        childViewHolder.autoResume();
                    } else {
                        childViewHolder.autoPause();
                    }
                }
            }
        }
    }

    @Subscribe(thread = ThreadMode.MAIN_THREAD, tags = {@Tag(Constants.MAINTABCHANGE)})
    public void rxMainTabChange(String data) {
        Logger.e("rxMainTabChange：" + data);

        if (mActivity != null) {
            if (isVisibleToTab) {
                mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            } else {
                mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            }
        }

        if (Integer.parseInt(data) == fragmentWhereTab) {
            if (!isVisibleToTab) {
                isVisibleToTab = true;
                if (playerPosition >= 0 && isVisibleToUser) {
                    VideoHolder childViewHolder = (VideoHolder) frvVideo.findViewHolderForAdapterPosition(playerPosition);
                    if (childViewHolder != null) {
                        childViewHolder.autoResume();
                    }
                }
            }
        } else {
            if (isVisibleToTab) {
                isVisibleToTab = false;
                if (playerPosition >= 0) {
                    VideoHolder childViewHolder = (VideoHolder) frvVideo.findViewHolderForAdapterPosition(playerPosition);
                    if (childViewHolder != null) {
                        childViewHolder.autoPause();
                    }
                }
            }
        }
    }

    @Override
    public boolean useRxBus() {
        return true;
    }
}
